package gene.core.sound;

import javax.microedition.media.Manager;
import javax.microedition.media.Player;

public class SoundPlayer {

    /**
     * constant SOUND PLAY
     */public static final int SOUND_PLAYING = 1;
    /**
     * constant SOUND STOP
     */public static final int SOUND_STOPPED = 2;
    /**
     * constant SOUND PLAY
     */public static final int STATE_SOUND_ON    = 1;
    /**
     * constant SOUND STOP
     */public static final int STATE_SOUND_OFF   = 2;
    /**
     * type
     *public static final int TYPE_FILE_MIDI=3;
     /**
      *
      *public static final int TYPE_FILE_MP3=4;
      /**
       *
       *public static final int TYPE_FILE_WAV = 5;
       /**
        *
        *private byte playerType = -1;
     /**
     */private byte state_volume[] = {0, 0};
    /**
     */public int volume = 100;
    /**
     *private StringBuffer filename = null;
    /**
     */private static Player tocador = null;    
     private int soundState = 0 ;

     public SoundPlayer(){
      state_volume[0]=2;
     }

    /**
     *
     * @param filename 
     * @param loop
     */
    public void playMusic(StringBuffer filename, boolean loop) {

        System.out.println("********** pass 0 stv "+state_volume[0]+" SD  "+soundState);
        if (this.state_volume[0] == SOUND_STOPPED && this.soundState == STATE_SOUND_ON) {
            this.state_volume[0] = SOUND_PLAYING;
            System.out.println("********** pass 1");
            try {
                tocador = Manager.createPlayer(filename.getClass().
                        getResourceAsStream(filename.toString()), "audio/midi");
                System.out.println("********** pass 2");
                if (loop) {
                    tocador.setLoopCount(-1);
                } else {
                    tocador.setLoopCount(1);
                }
                System.out.println("********** pass 3");
                tocador.realize();
                tocador.prefetch();
                tocador.start();
                System.out.println("********** pass 4");
                filename = null;

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println("********** pass 5");


        }

    }

    /**
     * 
     */
    public void stopMusic() {
        if (this.state_volume[0] == SOUND_PLAYING) {
            this.state_volume[0] = SOUND_STOPPED;
            try {
                tocador.stop();
                tocador.deallocate();
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }

    public int getSoundState(){
        return soundState;
    }
    public void setSoundState(int state){
        soundState = state;
    }
    public void destroy(){
        tocador.deallocate();
        tocador = null;
    }
}
